package com.store.app.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.bean.BookedBean;
import com.store.app.http.Stores;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.Utils;
import com.store.app.widget.DateTimeButton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Map;

/**
 * Created by Administrator on 2016/9/19.
 * 发起预售页面
 */
public class HuoPingCreateActivity extends BaseActivity implements IOnHttpListener {

    //标题
    private TextView title_tv;
    //商品名
    private TextView good_name;
    //商品图片
    private ImageView good_img;
    //商品规格
    private TextView good_guige;
    //商品起订量
    private TextView good_qiding;
    //商品市场价
    private TextView good_shichangjia;
    //商品优惠价
    private TextView good_money;
    //商品团购价
    private TextView good_money_edit;
    //数量加
    private TextView num_add;
    //数量
    private EditText num_tv;
    //数量减
    private TextView num_min;
    //截止时间
    private TextView end_date;
    //确认
    private TextView post_tv;
    private NetRequest netRequest;
    private String good_id;
    private DisplayImageOptions options;
    private DateTimeButton data_img;
    //数据bean
    private BookedBean bean;
    //团购价
    private String s_price;
    //数量
    private String s_num;
    //截止时间
    private String s_end_date;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_huoping_creat);
        good_id = getIntent().getStringExtra("goods_id");
        initView();
        initData();
        initListeners();
    }

    private void initView() {
        title_tv = (TextView) findViewById(R.id.tvTitle);
        good_name = (TextView) findViewById(R.id.huoping_tv_name);
        good_img = (ImageView) findViewById(R.id.huoping_img);
        good_guige = (TextView) findViewById(R.id.huoping_tv_guige);
        good_qiding = (TextView) findViewById(R.id.huoping_tv_qiding);
        good_shichangjia = (TextView) findViewById(R.id.huoping_tv_shichangjia);
        good_money = (TextView) findViewById(R.id.huoping_tv_money);
        good_money_edit = (EditText) findViewById(R.id.huoping_edit_money);
        num_add = (TextView) findViewById(R.id.huoping_relat3_add);
        num_tv = (EditText) findViewById(R.id.huoping_relat3_num);
        num_min = (TextView) findViewById(R.id.huoping_relat3_min);
        end_date = (TextView) findViewById(R.id.huoping_relat4_date);
        data_img = (DateTimeButton) findViewById(R.id.huoping_creat_date_btn);
        post_tv = (TextView) findViewById(R.id.huoping_tv_post);
    }

    private void initData() {
        title_tv.setText("发起预售");

        netRequest = new NetRequest(this);

        options = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .showImageOnLoading(R.drawable.default_picture_s)
                .showImageOnFail(R.drawable.default_picture_s)
                .showStubImage(R.drawable.default_picture_s)
                .imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        netRequest.requestGoodDetail(2, good_id, Stores.area_id);

    }

    private void initListeners() {
        findViewById(R.id.public_ll_return).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        data_img.setonDateListener(new DateTimeButton.DateListener() {

            @Override
            public void getdate(Calendar calendar) {
                String s_date = Utils.getTime1(calendar);
                Log.v("zyl", "s_date:" + s_date);
                if (!TextUtils.isEmpty(s_date)) {
                    end_date.setText(s_date);
                    end_date.setTextColor(getResources().getColor(R.color.text_color_black));
                }
            }
        });
        post_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                post();

            }
        });
        num_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bean == null) {
                    return;
                }
                int i_count = Integer.parseInt(num_tv.getText().toString());
//                int i_min_count=Integer.parseInt(bean.getMin_buy_qty());
                int sale_qty = Integer.parseInt(bean.getSale_qty());
                if (i_count < sale_qty) {
                    i_count = i_count + 1;
                }

                num_tv.setText(i_count + "");
            }
        });
        num_min.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bean == null) {
                    return;
                }
                int i_count = Integer.parseInt(num_tv.getText().toString());
                String minbuy_qty = bean.getMin_buy_qty();
                int i_min_count = 1;
                if (TextUtils.isEmpty(minbuy_qty) || Integer.parseInt(minbuy_qty) < 1) {
                    i_min_count = 1;
                } else {
                    i_min_count = Integer.parseInt(minbuy_qty);
                }

                if (i_count > i_min_count) {
//                    i_count = i_count - i_min_count;
                    i_count = i_count - 1;
                    num_tv.setText(i_count + "");

                }
            }
        });

    }

    public void post() {
        if (bean == null) {
            return;
        }
        s_price = good_money_edit.getText().toString().trim();
        if (TextUtils.isEmpty(s_price)) {
            Toast.makeText(HuoPingCreateActivity.this, "请输入团购价！", Toast.LENGTH_SHORT).show();
            return;
        }
        s_price = MoneyUtil.formatMoney(s_price);
        String markprice = bean.getMarket_price();
        String discountprice = bean.getDiscount_price();
        if (TextUtils.isEmpty(markprice)) {
            Toast.makeText(HuoPingCreateActivity.this, "提交失败！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(discountprice)) {
            Toast.makeText(HuoPingCreateActivity.this, "提交失败！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (MoneyUtil.moneyBigThan(s_price, markprice)) {
            Toast.makeText(HuoPingCreateActivity.this, "请输入小于建议零售价的团购价！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (MoneyUtil.moneyBigThan(discountprice, s_price)) {
            Toast.makeText(HuoPingCreateActivity.this, "请输入大于优惠价的团购价！", Toast.LENGTH_SHORT).show();
            return;
        }

        s_num = num_tv.getText().toString().trim();
        if (TextUtils.isEmpty(s_num)) {
            Toast.makeText(HuoPingCreateActivity.this, "请输入成团数量！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!MoneyUtil.moneyComp(s_num, bean.getMin_buy_qty())) {
            Toast.makeText(HuoPingCreateActivity.this, "成团数量必须大于起订量！", Toast.LENGTH_SHORT).show();
            return;
        }
        if(MoneyUtil.moneyBigThan(s_num,bean.getSale_qty())){
            Toast.makeText(HuoPingCreateActivity.this, "成团数量必须小于库存！", Toast.LENGTH_SHORT).show();
            return;
        }
        s_end_date = end_date.getText().toString();
        if (TextUtils.isEmpty(s_end_date) || s_end_date.equals("选择截止时间")) {
            Toast.makeText(HuoPingCreateActivity.this, "请输入截止时间！", Toast.LENGTH_SHORT).show();
            return;
        }


        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try

        {

            Date d1 = df.parse(s_end_date);

            Date d2 = new Date();

            long diff = d1.getTime() - d2.getTime();
            long days = diff / (1000 * 60);
            if (days >= 2880) {
                Toast.makeText(HuoPingCreateActivity.this, "请输入小于48小时的截止时间！", Toast.LENGTH_SHORT).show();
                return;
            }
            if (days < 60) {
                Toast.makeText(HuoPingCreateActivity.this, "截止时间需大于一小时！", Toast.LENGTH_SHORT).show();
                return;
            }
        } catch (Exception e)
        {

        }


        showProgressDialog("发起预售", "提交中……");
        netRequest.requestCreateHPT(1, num_tv.getText().toString(), end_date.getText().toString(), good_money_edit.getText().toString(), bean);

    }


    @Override
    public void onAfinalFail() {
        dismissProgressDialog();
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        Log.v("mylog", "onExecuteSuccess:" + result);
        if (requestId == 1) {
            dismissProgressDialog();
            Intent intent2 = new Intent(HuoPingCreateActivity.this, TheSingleOrderActivity.class);
            intent2.putExtra("showFragmentIndex", "3");
            startActivity(intent2);
            finish();
        } else if (requestId == 2) {
            Gson gson = new Gson();
            Type type = new TypeToken<BookedBean>() {
            }.getType();
            JSONObject obj1 = null;
            try {
                obj1 = new JSONObject(result);
                String docMap = obj1.getString("doc_url");
                JSONArray jsonList = obj1.getJSONArray("list");
                JSONObject jsonObject = jsonList.getJSONObject(0);
                bean = gson.fromJson(jsonObject.toString(), type);
                bean.setPic_info_url(docMap);
                good_name.setText(bean.getTitle());
                good_guige.setText("规格:" + bean.getSpecification());
                good_qiding.setText("起订量:" + bean.getMin_buy_qty());
                good_shichangjia.setText("建议零售价:" + bean.getMarket_price() );
                good_money.setText("¥" + bean.getDiscount_price());
                num_tv.setText(bean.getMin_buy_qty());
                String url = "";
                if (!TextUtils.isEmpty(bean.getPic_info())) {
                    try {
                        JSONArray jsonArray = new JSONArray(bean.getPic_info());
                        JSONObject jsonObject_img = jsonArray.getJSONObject(0);
                        String s_id = jsonObject_img.getString("path_id");
                        Map<String, String> map = Utils.getMapForJson(bean.getPic_info_url());
                        url = map.get(s_id);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    if (!TextUtils.isEmpty(bean.getPic_info_url()) && !("{}".equals(bean.getPic_info_url()))) {
                        Map map = Utils.getMapForJson(bean.getPic_info_url());
                        Collection<String> co = map.values();
                        url = co.iterator().next();

                    }
                }
                ImageLoader.getInstance().displayImage(url, good_img, options);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        Log.v("mylog", "onExecuteFail:" + msg);
        dismissProgressDialog();
        Toast.makeText(HuoPingCreateActivity.this, msg, Toast.LENGTH_SHORT)
                .show();
    }


}